package com.whsxt.utils;


import cn.hutool.core.date.DateUtil;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.File;
import java.util.Date;
import java.util.UUID;

public class FileUploadUtil {

    /**
     * 获取项目存放文件的路径
     * @return
     */
    public static String getProjectPath() {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        String projectPath = requestAttributes.getRequest().getRealPath("");

        return projectPath;
    }

    /**
     * 获取图片上传存放的路径
     * @param projectPath
     * @param originalFilename
     * @return
     */
    public static String getUploadPath(String projectPath, String originalFilename) {
        // 存放文件夹
        StringBuilder stringBuilder = new StringBuilder("images");
        // 附加日期时间路径
        stringBuilder.append(File.separator);
        String dateStr = DateUtil.format(new Date(), "yyyy-MM-dd");
        stringBuilder.append(dateStr);

        // 处理文件夹，如不存在文件夹则创建文件夹
        File file = new File(projectPath + File.separator + stringBuilder.toString());
        stringBuilder.append(File.separator);
        if (!file.exists()) {
            file.mkdirs();
        }

        // 通过原始名称 UUID得到新的名称
        stringBuilder.append(UUID.randomUUID().toString().replaceAll("-", ""));

        stringBuilder.append(originalFilename.substring(originalFilename.lastIndexOf(".")));
        return stringBuilder.toString();
    }
}
